<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\MallOrderComment;
use App\Models\Product;
use Illuminate\Http\Request;

class OrderCommentController extends BaseController
{

    public $model = MallOrderComment::class;

    public function index(Request $request) {
        $input = $request->input();
        $title = $request->input('title');
        $search = ['start_at' => '', 'end_at' => '', 'order_sn' => ''];
        $list = MallOrderComment::apply($search, $input)->when($title, function ($q) use($title) {
            $q->whereHas('order_product.product', function ($qt) use($title) {
               $qt->where('title', 'like', '%'.$title.'%');
            });
        })->withCertain('user', ['nickname', 'avatar_url', 'mobile'])
            ->withCertain('order_product.product', ['title', 'video_url', 'image_url'])
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        $info = null;
        return $this->paginate($list, $info);
    }


    /**
     * 删除
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function destroy(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required',
        ]);
        $input = $request->input();
        $arr_ids = explode(",", $input['ids']);

        try {
            return \DB::transaction(function () use ($arr_ids) {
                foreach ($arr_ids as $id) {
                    $entity_model = new Product();
                    $entity_model->where('id', $id)->increment('comment_num', -1);
                }
                return $this->success([], '删除成功');
            });
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed('删除失败 : ' . $e->getMessage());
        }
    }

    /**
     * 评论
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function reply(Request $request) {
        $this->validate($request, [
            'comment_id' => 'required',
            'reply_message' => 'required',
        ]);
        $user = $this->getUser();
        $input = $request->input();

        try {
            $id = \DB::transaction(function () use($input, $user){
                $model = MallOrderComment::find($input['comment_id']);
                if (!$model)
                    throw new \Exception('评论不存在');
                $model->reply_message = $input['reply_message'];
                $model->save();
                return $model->id;
            });
            return $this->success($id);
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }

    }

}

